<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{
          item.meta.title
        }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { compile } from 'path-to-regexp'

const route = useRoute()
const router = useRouter()
const levelList = ref<any[]>([])

// 监听路由变化
watch(
  () => route,
  () => {
    // 如果跳转到重定向页面，不更新面包屑
    if (route.path.startsWith('/redirect/')) {
      return
    }
    getBreadcrumb()
  },
  { immediate: true }
)

onMounted(() => {
  getBreadcrumb()
})

const getBreadcrumb = () => {
  // 只显示有 meta.title 的路由
  let matched = route.matched.filter(item => item.meta && item.meta.title)
  
  // 过滤掉不需要显示在面包屑中的路由
  matched = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
  
  levelList.value = matched
}

const isDashboard = (routeItem: any) => {
  const name = routeItem && routeItem.name
  if (!name) {
    return false
  }
  return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}

const pathCompile = (path: string) => {
  // 解决这个问题 https://github.com/PanJiaChen/vue-element-admin/issues/561
  const { params } = route
  const toPath = compile(path)
  return toPath(params)
}

const handleLink = (item: any) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(pathCompile(path))
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }

  .el-breadcrumb__item {
    :deep(.el-breadcrumb__inner a) {
      font-weight: 400 !important;
    }
  }
}
</style>